/*******************************************************************************
 * Package: com.song.boot.springstudy.thread.concurrent
 * Type:    MyCountDownLatch
 * Date:    2023-02-05 17:14
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.thread.concurrent;

import com.google.common.collect.Lists;
import com.song.common.work.SplitListUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * 功能描述： 学习 CountDownLatch、CompletableFuture 搭配使用
 * 帮助文档：https://mp.weixin.qq.com/s/0qc-ddbxY7bOHywQkYe80w
 *CompletableFuture：https://juejin.cn/post/7134708925857234980#heading-3
 * 会存在的问题：https://juejin.cn/post/7129116234804625421
 *  阻塞队列中已经塞满了，所以默认的拒绝策略，当队列满时，处理策略报错异常，
 * @author Songxianyang
 * @date 2023-02-05 17:14
 */
public class MyCountDownLatch {
    public static final String SONG="---宋先阳";
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 初始化线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(20);
        List<Integer> list = new ArrayList<>();
        // 往集合中添加数据
        IntStream.rangeClosed(0,20).forEach(list::add);
        // 集合分段
        List<List<Integer>> lists = SplitListUtils.split(list, 10);
        // 记录单个任务的执行次数
        CountDownLatch downLatch = new CountDownLatch(lists.size());
        // 新增数据的list
        List<String> insertList = Lists.newArrayList();

        for (List<Integer> integerList : lists) {
            // 有返回值的API
            CompletableFuture<List<String>> listCompletableFuture = CompletableFuture.supplyAsync(() ->
                    // 封装处理返回值的方法
                    getStrings(integerList),
                    // 自定义的线程池
                    threadPool
            );
            // 获取线程中结果放入：新增数据的list
            insertList.addAll(listCompletableFuture.get());
            // 任务个数 - 1, 直至为0时唤醒await()
            downLatch.countDown();
            System.out.println("个数：：：："+downLatch.getCount());
        }

        // 让当前线程处于阻塞状态，直到锁存器计数为零
        downLatch.await();
        // 批量新增
        if (!CollectionUtils.isEmpty(insertList)) {
            // 执行DAO中的批量新增：
            System.out.println(insertList);
        }

    }

    private static List<String> getStrings(List<Integer> integerList) {
        List<String> childList  = Lists.newArrayList();
        for (Integer integer : integerList) {
            String s=integer+SONG;
            childList.add(s);
        }
        return childList;
    }
}
